﻿using AutoMapper;
using DFGK.IRepository;
using DFGK.IService;
using DFGK_WMS.Model.Models;
using NPOI.SS.Formula.Functions;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Yitter.IdGenerator;

namespace DFGK.Service
{
    public class DepartMentService : BaseService, IDepartMentService
    {
        private readonly IDepartMentRepository _departMentRepository;
        private readonly IUnitOfWork _unitOfWork;
        public DepartMentService(IMapper mapper, IDepartMentRepository departMentRepository, IUnitOfWork unitOfWork) : base(mapper)
        {
            _departMentRepository = departMentRepository;
            _unitOfWork = unitOfWork;
        }
        public bool AddDepartMentList(List<Department> departments, out string message)
        {
            message = string.Empty;

            foreach (var item in departments)
            {
                try
                {
                    // 生成唯一ID
                    item.Id = YitIdHelper.NextId();

                    // 检查Code是否重复
                    var existingMaterial = _departMentRepository.QueryIsEntityWhere(x => x.DepartmentCode == item.DepartmentCode);
                    if (existingMaterial != null)
                    {
                        message = $"{item.DepartmentCode}编码已存在";
                        return false;
                    }

                    // 添加单条记录
                    _departMentRepository.AddEntity(item);

                    // 提交事务
                    var result = _unitOfWork.SaveChangesEntity();
                    if (!result)
                    {
                        message = "提交失败，请重试";
                        return false;
                    }
                }
                catch (Exception ex)
                {
                    message = $"添加失败：{ex.Message}";
                    // 记录异常日志
                    return false;
                }
            }

            return true;




        }
        public List<Department> GetAllDepartment(string? name, int pageIndex, int pageSize, out int totalCount)
        {
            var custList = _departMentRepository.GetEntityAlls();
            if (!string.IsNullOrEmpty(name))
            {
                custList = custList.Where(c => c.DepartmentName.Contains(name));
            }
            var list = _departMentRepository.GetEntityAlls(custList, pageIndex, pageSize, out totalCount, x => x.CreateDate, false);
            return list.ToList();
        }
    }
}
